package com.chuyu.cy.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuyu.cy.entity.domain.TemporaryNeeds;
import com.chuyu.cy.service.TemporaryNeedsService;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: white-zhou
 * @date: 2024-03-22 19:42
 * @description: 逾期需求任务处理
 **/
@Component
public class OverdueNeedJob {

    @Resource
    private TemporaryNeedsService temporaryNeedsService;


    // 每12小时执行一次 0 0 0/12 * * ?
    @Scheduled(cron = "0 0 0/12 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void execute() {
        // 逾期需求处理
        LambdaQueryWrapper<TemporaryNeeds> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TemporaryNeeds::getIsMatched, 0);

        List<TemporaryNeeds> list = temporaryNeedsService.list(queryWrapper);
        if (list.isEmpty()) {
            return;
        }

        // 逾期需求处理逻辑
        ArrayList<Integer> deleteIds = new ArrayList<>();
        for (TemporaryNeeds temporaryNeeds : list) {
            LocalDateTime limitTime = temporaryNeeds.getLimitTime();
            LocalDateTime now = LocalDateTime.now();
            // 判断是否逾期
            if (!now.isAfter(limitTime)) {
                // 未逾期
                continue;
            }

            // 逾期则删除
            deleteIds.add(temporaryNeeds.getId());
        }

        // 删除逾期需求
        if (!deleteIds.isEmpty()) {
            temporaryNeedsService.removeByIds(deleteIds);
        }
    }
}
